package com.kly.user.task.v2.adjust;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.UserAdjustReportDao;
import com.kly.user.db.dao.UserAdjustReportDetailDao;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.entity.UserAdjustReportDetailEntity;
import com.kly.user.db.entity.UserAdjustReportEntity;
import com.kly.user.db.entity.UserEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * adjust数据解析
 * @author linqu
 */
@Service
public class AdjustReportTask {

    private static Log logger = LogFactory.getLog(AdjustReportTask.class);

    private String localIP = NetUtil.getLocalhostStr();
    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;
    @NacosValue(value = "${analysis.adjust.report.switch:true}", autoRefreshed = true)
    private Boolean analysisAdjustReportSwitch;
    @Resource
    UserAdjustReportDao userAdjustReportDao;
    @Resource
    UserAdjustReportDetailDao adjustReportDetailDao;
    @Resource
    UserDao userDao;



    /**
     * 执行频率：10分钟
     */
    @Scheduled(fixedDelay = 1000 * 600)
    public void analysisAdjustReport() {
        logger.info("====analysisAdjustReport start");
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============analysisAdjustReport, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        if (!analysisAdjustReportSwitch) {
            logger.info("=============analysisAdjustReportSwitch:{}", analysisAdjustReportSwitch);
            return;
        }


        final List<UserAdjustReportEntity> userAdjustReportEntities = userAdjustReportDao.listAdjustRecord();
        if (CollectionUtils.isEmpty(userAdjustReportEntities)) {
            return;
        }

        for (UserAdjustReportEntity o : userAdjustReportEntities) {
            analysisReport(o);
        }

    }


    private void analysisReport(UserAdjustReportEntity o) {
        try {
            final JSONObject json = JSONObject.parseObject(o.getReportContent());
            if (json == null) {
                return;
            }

            // 添加解析数据
            final UserAdjustReportDetailEntity detail = addAdjustReportDetail(o, json);

            // 修复channel
            if (StringUtils.isNotEmpty(detail.getAdId())) {
                if (StringUtils.isNotEmpty(detail.getChannel()) && "Unattributed".equals(detail.getChannel())) {
                    final UserEntity user = userDao.getUserByAdid(detail.getAdId());
                    if (user != null && ("Unattributed".equals(user.getChannel()) || StringUtils.isEmpty(user.getChannel()))) {
                        user.setChannel(detail.getChannel());
                        userDao.update(user);
                    }
                }
            }


            // 设置解析成功状态
            o.setAnalysisFlag(1);
            userAdjustReportDao.updateByPrimaryKey(o);

        } catch (Exception e) {
            logger.error("analysisAdjustReportFailed, id:{}", o.getId(), e);
            o.setAnalysisFlag(2);
            userAdjustReportDao.updateByPrimaryKey(o);
        }
    }

    private UserAdjustReportDetailEntity addAdjustReportDetail(UserAdjustReportEntity o, JSONObject json) {
        UserAdjustReportDetailEntity entity = new UserAdjustReportDetailEntity();
        entity.setReportCode(o.getReportCode());
        entity.setAdId(json.getString("adid"));
        String channel = json.containsKey("network_name") ? json.getString("network_name") : "";
        if ("Unattributed".equals(channel)) {
            channel = json.getString("meta_install_referrer_publisher_platform");
        }
        entity.setChannel(channel);
        entity.setOsVersion(json.getString("os_version"));
        entity.setDeviceName(json.getString("device_name"));
        entity.setIpAddress(json.getString("ip_address"));
        entity.setCountry(json.getString("country"));
        entity.setCity(json.getString("city"));
        entity.setCountrySubdivision(json.getString("country_subdivision"));
        String campaignGroupName = json.containsKey("fb_install_referrer_campaign_group_name") ? json.getString("fb_install_referrer_campaign_group_name") : "";
        if (StringUtils.isEmpty(campaignGroupName)) {
            campaignGroupName = json.getString("meta_install_referrer_campaign_group_name");
        }
        entity.setCampaignGroup(campaignGroupName);

        String campaignName = json.containsKey("fb_install_referrer_campaign_name") ? json.getString("fb_install_referrer_campaign_name") : "";
        if (StringUtils.isEmpty(campaignName)) {
            campaignName = json.getString("meta_install_referrer_campaign_name");
        }
        entity.setCampaignName(campaignName);

        String adGroupName = json.containsKey("fb_install_referrer_adgroup_name") ? json.getString("fb_install_referrer_adgroup_name") : "";
        if (StringUtils.isEmpty(adGroupName)) {
            adGroupName = json.getString("meta_install_referrer_adgroup_name");
        }
        entity.setAdgroupName(adGroupName);
        entity.setLanguage(json.getString("language"));
        adjustReportDetailDao.insert(entity);

        return entity;
    }
}